#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "menu.h"
#include "test.h"

int TestHelp(int argc, char *argv[]);

COMMAND_TABLE CommandTable[] = {
    {"HELP","List the command",TestHelp},
    {"RAND",NULL,TestRand},
    {"MULT",NULL,TestMultiple},
    {"PRIME",NULL,TestPrime},
    {"GOL",NULL,TestGoldbach},
    {"PSH1",NULL,TestPsh1},
    {"PSH2",NULL,TestPsh2},
    {"TOK","Test My strtok function",TestMystrtok},
    {"PRO",NULL,TestProtocol},
    {"ARG","Test the argument",TestArgs},
    {"MARGV","Test the makeargv",Testargv},

};

int is_exit_cmd(const char *cmd)
{
    char str[80];

    int len = (sizeof(str) > (strlen(cmd) + 1) ? (strlen(cmd) + 1): (sizeof(str)));
    strncpy(str,cmd,len);

    TurnToupper(str);
    return strcmp(str,"EXIT");
}


int ExcuteCommand(const char *Command)
{
    int i;  
    int status = 1;

    char str[80];
    int length = sizeof(CommandTable)/sizeof(COMMAND_TABLE);

    if (strcmp(Command,"") == 0) {
        return status;
    }
    int len = (sizeof(str) > (strlen(Command) + 1) ? (strlen(Command) + 1): (sizeof(str)));
    strncpy(str,Command,len);
    TurnToupper(str);
    for (i=0;i<length;i++){
        if (str_equ(CommandTable[i].Cmd,str)){
            status = CommandTable[i].Function(0,NULL);  // error:-1,success:0,unexecute:1
            break;
        }
    }
    if (status == 1) {
        printf("Can not find the command: \"%s\".\nEnter 'help' to get the usage info.\n",Command);
    }
    printf(":)");

    return status;
 }

void TurnToupper(char * str)
{
    if (str == NULL){
        return;
    }
    while(*str)
    {
        *str = _toupper(*str);
        str++;
    }

}

int TestHelp(int argc, char *argv[])
{
    int suffix;
    int length = sizeof(CommandTable)/sizeof(COMMAND_TABLE);

    printf("\n%-15s%s","Command","Description\n");

    for (suffix=0;suffix<length;suffix++) {
        printf("%-15s%s\n",CommandTable[suffix].Cmd,CommandTable[suffix].help);
    }
    return 0;
}
